<?php
class finance extends core {
	public function __construct() {
		parent::__construct();
	}

	//index
	public function index() {
		$sql = "SELECT * FROM jf_beautyshop_withdraw WHERE shop_id='{$this->shopadmin_id}' ORDER BY id DESC";
		$rs = $this->ezr->get_results($sql);
		if ($rs) {
			foreach ($rs as $key => $row) {
				$rs[$key]['add_time'] = date('Y-m-d H:i:s',$row['add_time']);
				$rs[$key]['audit_time_str'] = date('Y-m-d H:i:s',$row['audit_time']);
			}
		}
		$nav = $this->ezr->get_navigation();
		$this->smarty->assign('rs',$rs);
		$this->smarty->assign('page',$nav);
		
		//未提现金额
		$sql = "SELECT SUM(total_price) FROM jf_order WHERE shop_id='{$this->shopadmin_id}' AND is_jiesuan=1 AND withdraw_time=0";
		$price = $this->db->get_var($sql);
		$this->smarty->assign('total_price',$price-$price*0.05);
		
		//可提现金额
		$sql = "SELECT last_order FROM jf_beautyshop_withdraw WHERE shop_id='{$this->shopadmin_id}' AND status>-1 ORDER BY id DESC LIMIT 1";
		$last_order = $this->db->get_var($sql);
		if (!$last_order) $last_order = 0;
		$time =  strtotime(date("Y-m-d", strtotime("last sunday")).' 23:59:59');
		$sql = "SELECT SUM(total_price) FROM jf_order WHERE shop_id='{$this->shopadmin_id}' AND is_jiesuan=1 AND withdraw_time=0 
				AND id>'{$last_order}' AND add_time<='{$time}'";
		$price = $this->db->get_var($sql);
		$this->smarty->assign('can_price',$price-$price*0.05);
		
		$this->smarty->assign('now',date('Y-m-d H:i:s'));
		$this->display();
	}

	//apply
	public function apply() {
		$price = (isset($_POST['price'])) ? intval($_POST['price']) : 0;
		if ($price<=0) exit;
		
		$sql = "SELECT last_order FROM jf_beautyshop_withdraw WHERE shop_id='{$this->shopadmin_id}' AND status!='-1' ORDER BY id DESC";
		$last_order = $this->db->get_var($sql);
		if (!$last_order) $last_order = 0;
		$time =  strtotime(date("Y-m-d", strtotime("last sunday")).' 23:59:59');
		$sql = "SELECT SUM(total_price) FROM jf_order WHERE shop_id='{$this->shopadmin_id}' AND is_jiesuan=1 AND withdraw_time=0 
				AND id>'{$last_order}' AND add_time<='{$time}'";
		$price = $this->db->get_var($sql);
		if ($price<=0) exit;
		
		$orders = array();
		$sql = "SELECT id FROM jf_order WHERE shop_id='{$this->shopadmin_id}' AND is_jiesuan=1 AND withdraw_time=0 
				AND id>'{$last_order}' AND add_time<='{$time}' ORDER BY id ASC";
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $key => $row) {
				$orders[] = $row->id;
			}
		}
		if (count($orders)) $last_order = $orders[count($orders)-1];
		//exit(implode(',',$orders));
		
		$sql = "INSERT INTO jf_beautyshop_withdraw(shop_id, price, orders, last_order, ip, status, add_time)
				VALUES('{$this->shopadmin_id}', '".round(($price-$price*0.05),2)."', '".implode(',',$orders)."', '{$last_order}', '".ip()."', '0', '".time()."')";
		$this->db->query($sql);
		
		echo '<meta charset="UTF-8"><script>alert("申请已提交，请耐心等待审核");location.href="?app=finance&act=index";</script>';
		exit;
	}
}
